package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2021-11-02
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    /**
     * 频道分页条件查询
     *
     * @param dto
     * @return ResponseResult:统一响应对象   子类：PageResponseResult 分页响应对象
     */
    @Override
    public ResponseResult listByName(ChannelDto dto) {
        IPage<WmChannel> pageInfo = new Page<>();
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            queryWrapper.like(WmChannel::getName, dto.getName());
        }
        this.page(pageInfo, queryWrapper);
        PageResponseResult responseResult = new PageResponseResult<>(dto.getPage(), dto.getSize(), pageInfo.getTotal(), pageInfo.getRecords());
        return responseResult;
    }

    /**
     * 保存频道
     *
     * @param channel
     * @return
     */
    @Override
    public void saveChannel(WmChannel channel) {
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName, channel.getName());
        int count = this.count(queryWrapper);
        if (count == 0) {
            channel.setIsDefault(false);
            channel.setOrd(0);
            channel.setStatus(false);
            this.save(channel);
        } else {
            throw new RuntimeException("频道已存在");
        }
    }
}
